package plp.prolog.parser;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class TestProvider {
	private ArrayList<Pair<String, File> > listFiles;
	private static final String BASE_PATH = "./tests";

	public ArrayList<Pair<String, File> > getFileTests(){
		listFiles = new ArrayList<Pair<String, File>>();

		File baseDir = new File(BASE_PATH);
		this.readDirectory(baseDir);
		
		return listFiles;
	
	}

	private void readDirectory(File file){
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++)
				readDirectory(files[i]);
		}else{
			readFile(file);
		}

	}

	private void  readFile(File file) {
		String fileName = file.getName();
//		String fileContent = getFileContent(file);

		Pair<String, File> newFile = new Pair<String, File>(fileName, file);

		listFiles.add(newFile);

	}

	private String getFileContent(File file){
		String fileContent = "";
		
		try{
			FileInputStream fstream = new FileInputStream(file);

			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;

			while ((strLine = br.readLine()) != null)   {
				fileContent += " " + strLine;
			}

			in.close();
		}catch (Exception e){
			System.err.println("Error: " + e.getMessage());
		}
	
		return fileContent;
	}
	
	
	public boolean saveTestResult(TestStatusManager tsm) {
		FileWriter outFile;
		try {
			Calendar cal = GregorianCalendar.getInstance();
			
			int day = cal.get(Calendar.DAY_OF_WEEK);
			int month = cal.get(Calendar.MONTH);
			int year = cal.get(Calendar.YEAR);
			
			int hour = cal.get(Calendar.HOUR);
			int min  = cal.get(Calendar.MINUTE);
			int sec  = cal.get(Calendar.SECOND);
			
			String fileName = "result_" + day + month + year + "_" + hour + min + sec + ".txt";
			outFile = new FileWriter("./results/" + fileName);
			PrintWriter out = new PrintWriter(outFile);
			
			String fullDate = String.format("%02d/%02d/%4d - %02d:%2d", day, month, year, hour, min);
			out.println("TEST RESULT");
			out.println("DATE	: " + fullDate);
			out.println("SUMMARY	:");
			
			for (String s :tsm.getSummary()) {
				out.println(s);
			}

			out.println("");
			out.println("Detailed result");
			
			for (String s : tsm.getDetailedResult()) {
				out.println(s);
			}
			
			out.close();
		} catch (IOException e) {
			return false;
		}
		
		return true;
	}
}
